part of 'logger.dart';

class HttpLog extends Log {
  String? url;
  Map<String, dynamic>? headers;
  Map<String, dynamic>? params;
  int? statusCode;
  Map<String, dynamic>? response;
  int? totalTime;
  String? curl;
  Map<String, dynamic>? body;

  bool get isSuccess => statusCode! >= 200 && statusCode! < 300;

  HttpLog() {
    this.type = LogType.http;
  }

  ApiDocSummary? _apiSummaryBean;

  ApiDocSummary? get summary => _apiSummaryBean ??= queryApiSummaryBy(url);

  HttpLog.fromJson(Map<String, dynamic> json) {
    type = LogType.http;
    time = DateTime.tryParse(json['time']);
    url = json['url'];
    headers = json['headers'];
    params = json['params'];
    statusCode = json['statusCode'];
    response = json['response'];
    totalTime = json['totalTime'];
    body = json['body'];
    curl = json['curl'];
  }

  Map<String, dynamic> toJson() {
    return {
      "type": type.toString(),
      "time": time?.format(timePatternYearMonthHourMinuteSecondSlash),
      "url": url,
      "headers": headers,
      "params": params,
      "statusCode": statusCode,
      "response": response,
      "totalTime": totalTime,
      "body": body,
      "curl": curl
    };
  }
}

class ExceptionLog extends Log {
  late String exception;
  late String stack;

  ExceptionLog(this.exception, this.stack) {
    this.type = LogType.exception;
  }

  ExceptionLog.fromJson(Map<String, dynamic> json) {
    type = LogType.exception;
    time = DateTime.tryParse(json['time']);
    exception = json['exception'];
    stack = json['stack'];
  }

  Map<String, dynamic> toJson() {
    return {
      "type": type.toString(),
      "time": time?.format(timePatternYearMonthHourMinuteSecondSlash),
      "exception": exception,
      "stack": stack
    };
  }
}

class NormalLog extends Log {
  late String message;

  NormalLog(this.message) {
    this.type = LogType.normal;
  }

  NormalLog.fromJson(Map<String, dynamic> json) {
    type = LogType.exception;
    time = DateTime.tryParse(json['time']);
    message = json['msg'];
  }

  Map<String, dynamic> toJson() {
    return {
      "type": type.toString(),
      "time": time?.format(timePatternYearMonthHourMinuteSecondSlash),
      "msg": message
    };
  }
}

class Log {
  late LogType type;
  DateTime? time;

  Log() {
    time = DateTime.now();
  }
}

enum LogType { http, exception, normal }
